<template>
  <div class="alert_download">
    <a-alert class="a-alert">
      <template #icon>
        <icon-exclamation-circle />
      </template>
      <div class="alert-item">
        电子合同生成后，支持在签署中状态通过【修改合同】变更电子合同的内容，已完成签署和已作废后不支持变更合同内容。
      </div>
    </a-alert>
    <div class="ml-3" v-permission="getPermission('handContract')">
      <a-button type="primary" @click="() => onClick()">手动生成电子合同</a-button>
    </div>
    <div class="download-button" v-permission="getPermission('batchdownload')" @click="downLoadAll({ orderCode: orderCode })">
      批量下载
    </div>
  </div>
  <table-index
    :table="tableCompulsory"
    @loadData="loadCompulsoryData"
    @selection-change="selectionChange"
    @pagenationChange="pagenationChange"
  >
    <template #contractStatus="{ record }">
      <div :class="'contract-statusname contract-statusname-' + record.contractStatus">{{ record.contractStatusName }}</div>
      <!-- 生成失败 -->
      <div v-if="record.contractStatus == -1" class="res-button" @click="errorShow(record)">原因</div>

      <!-- 签署中 -->
      <div v-if="record.contractStatus == 2 || record.contractStatus == 3 || record.contractStatus == 8">
        <!-- 承租方 -->
        <div class="status_copys">
          <div>承租方</div>
          <div v-if="record.lesseeSignStatus == 1" class="lessee_sign lessee_sign_status_1">{{ record.lesseeSignStatusName }}</div>
          <div v-if="record.lesseeSignStatus == 2" class="lessee_sign lessee_sign_status_2">{{ record.lesseeSignStatusName }}</div>
          <div
            v-if="record.lesseeSignStatus == 1 || record.contractStatus == 3 || record.contractStatus == 8"
            class="copy_link"
            v-permission="getPermission('contractCopySigningLink')"
            @click="getLesseeSignUrl(record)"
          >
            <img src="@/assets/link.png" />
            <span> 复制合同链接 </span>
          </div>
        </div>
        <!-- 出租方 -->
        <div class="status_copys">
          <div>出租方</div>
          <div v-if="record.hireSignStatus == 1" class="lessee_sign lessee_sign_status_1">{{ record.hireSignStatusName }}</div>
          <div v-if="record.hireSignStatus == 2" class="lessee_sign lessee_sign_status_2">{{ record.hireSignStatusName }}</div>
        </div>
      </div>

      <!-- 作废中 -->
      <div v-if="record.contractStatus == 7">
        <!-- 承租方 -->
        <div class="status_copys">
          <div>承租方</div>
          <div v-if="record.lesseeInvalidedStatus == 1" class="lessee_sign lessee_sign_status_1">
            {{ record.lesseeInvalidedStatusName }}
          </div>
          <div v-if="record.lesseeInvalidedStatus == 2" class="lessee_sign lessee_sign_status_2">
            {{ record.lesseeInvalidedStatusName }}
          </div>
          <div
            v-if="record.lesseeInvalidedStatus == 1"
            class="copy_link"
            v-permission="getPermission('contractCopyVoidLink')"
            @click="getLesseeSignUrl(record)"
          >
            <img src="@/assets/link.png" />
            <span> 复制作废链接 </span>
          </div>
        </div>
        <!-- 出租方 -->
        <div class="status_copys">
          <div>出租方</div>
          <div v-if="record.hireInvalidedStatus == 1" class="lessee_sign lessee_sign_status_1">{{ record.hireInvalidedStatusName }}</div>
          <div v-if="record.hireInvalidedStatus == 2" class="lessee_sign lessee_sign_status_2">{{ record.hireInvalidedStatusName }}</div>
        </div>
      </div>
    </template>
    <template #lessee="{ record }">
      <div v-if="record.leaseType == 1">{{ record.lesseeCompanyName }}</div>
      <div v-else>{{ record.lesseeName }}</div>
    </template>

    <!-- 长租显示合同属性 -->
    <template #attribute v-if="orderType && orderType == 2">
      <div>合同属性</div>
    </template>
  </table-index>
  <!-- 更换车牌 -->
  <addPhone ref="addphones" @ok="addphoneFn" />
  <!-- 完善信息 -->
  <ImproveInformationModal :type="type" :modal-alert="modalAlert" ref="improveInformationRef" @onOk="improveInformationOnOk" />
  <!-- 生成电子合同 -->
  <ViewContractModal v-model:visible="viewVisible" v-model:loading="viewLoading" :order="viewContractInfo" @on-ok="onOkContract" />
  <!-- 修改承租人信息 -->
  <shortEditLesseeMemberModal isCommonContract v-if="orderType == 1" ref="editLesseeMemberModalRef" @ok="onModalOkFn" />
  <longEditLesseeMemberModal isCommonContract v-else ref="editLesseeMemberModalRef" @ok="onModalOkFn" />
  <!-- 选择车牌号 -->
  <change-license-modal ref="changeLicenseModalRef" :orderCarInfoList="orderCarInfoList" @ok="changeLicenseOk" />
  <!-- 排车 -->
  <car-selector :title="carSelectorModalTitle" :isLongOrder="orderType == 2" ref="carSelectorRef" @ok="onModalOkFn" />
  <!-- 修改已选承租人信息 -->
  <EditCurrentMemberModal
    :orderType="orderType == 1 ? 'sOrder' : 'lOrder'"
    ref="editCurrentMemberModalRef"
    @changeMember="changeMemberFn"
    @ok="onModalOkFn"
    isCommonContract
  />
  <!-- 预览pdf -->
  <pdf-viewer
    :url="pdfViewInfo.url"
    :title="pdfViewInfo.title"
    v-model:visible="pdfViewInfo.show"
    @close="Object.assign(pdfViewInfo, { ...PDFDefaultAttr })"
  />
</template>
<script setup lang="ts">
  import ImproveInformationModal from '@/views/order/modals/improve-information-modal.vue'
  import shortEditLesseeMemberModal from '@/views/order/short-order/components/list-modals/edit-lessee-member-modal.vue'
  import longEditLesseeMemberModal from '@/views/order/long-order/components/list-modals/edit-lessee-member-modal.vue'
  import EditCurrentMemberModal from '@/views/order/components/customer/edit-current-member-modal.vue'
  import ViewContractModal from '@/views/order/modals/view-contract-modal.vue'
  import carSelector from '@/views/assets/car/stock/car-selector.vue'
  import changeLicenseModal from '../../components/list-modals/change-license-modal.vue'
  import clipboard3 from 'vue-clipboard3'
  import addPhone from '@/views/order/short-order/detail/components/add-phone.vue'
  import { usePermission } from '@/hooks/usePermission'
  import { ref, onMounted, inject, h, reactive } from 'vue'
  import { useTable } from '@/hooks/table'
  import {
    signRecordAPI,
    contractRecordAPI,
    initiateAPI,
    nullifyAPI,
    determineAPI,
    revokeAPI,
    getLesseeSignUrlAPI,
    createQysContractAPI,
    createContractAPI,
    getShortOrdrDetails,
    getContractInfo,
    updateFreeContract,
    checkContractData,
    carReplaceList,
  } from '@/api/order/sOrder'
  import { getLongOrderDetails, updateReplaceList } from '@/api/order/czsOrder'
  import { sendLesseeSignMsg } from '@/api/business/contract'
  import { getDetail, clientupdate } from '@/api/market/clientInfo'
  import { Message, Modal } from '@arco-design/web-vue'
  import request from '@/api/axios.config'
  import useNavigate from '@/hooks/useNavigate'
  import { targetStrColor } from '@/utils'

  // pdf预览
  import { PDFDefaultAttr } from '@/components/pdf-viewer/const'
  const pdfViewInfo = reactive({ ...PDFDefaultAttr })

  const { navigateTo } = useNavigate()
  const { toClipboard } = clipboard3()
  const orderCode = ref()
  const copyurl = ref() //复制承租方链接
  const clientData = ref() //企业联系人信息
  const addphones = ref()
  const selectedRowKeys = ref([])
  const emits = defineEmits(['ok'])
  const props = defineProps({
    orderId: Number,
    orderType: Number,
    payType: Number,
    contractAttribute: Number,
    permissionPrefix: String,
  })
  const type = ref('person')
  const modalAlert = ref('')
  const viewVisible = ref(false)
  const viewLoading = ref(false)
  const getContractCountShortOrder = inject<any>('getContractCountShortOrder')
  const getContractCountLongOrder = inject<any>('getContractCountLongOrder')

  // 传入的是后缀，拼接前缀+.+后缀
  const getPermission = (permissionSubfix: string) => {
    return props.permissionPrefix + '.' + permissionSubfix
  }

  const selectionChange = (e: any) => {
    selectedRowKeys.value = e
  }

  // 页数选择后清空 复选框
  const pagenationChange = () => {
    selectedRowKeys.value = []
  }
  // 列表里点击失败原因
  const errorShow = (record: any) => {
    if (record.createErrorCode == 1001) {
      // 1. 姓名手机号不匹配时
      toError(record)
    } else {
      // 2. 其他原因（没有前往修改按钮）
      Modal.confirm({
        title: '提示',
        simple: true,
        hideCancel: true,
        okText: '关闭',
        content: record.createErrorReason,
      })
    }
  }
  // 去修改订单
  const toError = (record: any) => {
    Modal.confirm({
      title: '提示',
      simple: true,
      cancelText: '关闭',
      okText: '前往修改',
      content: '请将承租人姓名修改为上次已通过实名认证的姓名，再进行重新生成合同的操作。',
      onOk: () => {
        if (props.orderType == 1) {
          navigateTo(`/short-order/edit/${props.orderId}`, `${record.orderCode}-修改订单`)
        } else {
          navigateTo(`/long-order/edit/${props.orderId}`, `${record.orderCode}-修改订单`)
        }
      },
      onCancel: () => {
        loadCompulsoryData()
      },
    })
  }
  // 批量下载
  const downLoadAll = (record: any) => {
    console.log(record)
    if (selectedRowKeys.value.length) {
      console.log(selectedRowKeys.value)
      if (props.orderType == 1) {
        request
          .post(
            '/svmsContract/butchDownloadContractFile',
            {
              idList: selectedRowKeys.value,
            },
            {
              responseType: 'blob',
            }
          )
          .then((res) => {
            console.log(res)
            fileDownload(res.data, 'all', record)
          })
      } else {
        request
          .post(
            '/svmsContract/butchDownloadContractFile',
            {
              idList: selectedRowKeys.value,
            },
            {
              responseType: 'blob',
            }
          )
          .then((res) => {
            console.log(res)
            fileDownload(res.data, 'all', record)
          })
      }
    } else {
      Message.warning('请勾选需要下载的合同')
    }
  }
  // 文件下载
  const fileDownload = (_res: any, tp: any, record: any) => {
    console.log(record)
    var name = ''
    var blob: any
    if (tp == 'all') {
      // 批量下载
      name = record.orderCode
      blob = new Blob([_res], { type: 'application/zip' })
    }
    if (tp == 'justone') {
      // 单个下载
      name = record.contractTypeName + record.contractNo
      blob = new Blob([_res], { type: 'application/pdf' })
    }
    let downloadElement = document.createElement('a')
    let href = window.URL.createObjectURL(blob) //创建下载的链接
    downloadElement.href = href
    // downloadElement.download = fileName; //下载后文件名
    downloadElement.download = name //下载后文件名
    document.body.appendChild(downloadElement)
    downloadElement.click() //点击下载
    document.body.removeChild(downloadElement) //下载完成移除元素
    window.URL.revokeObjectURL(href) //释放掉blob对象
  }
  // 生成合同
  const contractGet = (record: any) => {
    createQysContractAPI({ id: record.id }).then((res: any) => {
      console.log(res)
      if (res.result.createErrorCode) {
        if (res.result.createErrorCode == 1001) {
          // 生成失败弹窗
          // 1. 姓名手机号不匹配时
          toError(record)
        } else {
          // 生成失败弹窗
          // 2. 其他原因（没有前往修改按钮）
          Modal.confirm({
            title: '提示',
            simple: true,
            hideCancel: true,
            okText: '关闭',
            content: res.result.createErrorReason,
          })
          loadCompulsoryData()
        }
      } else if (res.result.createErrorCode == null) {
        Message.success('操作成功')
        loadCompulsoryData()
      }
    })
  }
  // 数据
  const loadCompulsoryData = () => {
    var param
    if (props.orderType == 1) {
      // 短租
      param = {
        id: props.orderId,
        orderCode: orderCode.value,
        orderType: props.orderType,
        pageNumber: 1,
        pageSize: 1000,
        payType: props.payType,
      }
      tableCompulsory.tableLoading = true
      contractRecordAPI(param)
        .then((res: any) => {
          // order.value = res.result
          const data = res.result //表
          data.forEach((i: any) => {
            if (i.contractStatus == 3 || i.contractStatus == 7 || i.contractStatus == 8 || i.contractStatus == 10) {
              i.disabled = false
            } else {
              i.disabled = true
            }
          })
          tableCompulsory.dataList = data
          if (tableCompulsory.dataList.length) {
            orderCode.value = tableCompulsory.dataList[0].orderCode
          }
        })
        .finally(() => {
          tableCompulsory.tableLoading = false
        })
    } else {
      // 长租
      param = {
        orderId: props.orderId,
        pageNumber: 1,
        pageSize: 1000,
        contractAttribute: props.contractAttribute,
      }

      tableCompulsory.tableLoading = true
      signRecordAPI(param)
        .then((res: any) => {
          // order.value = res.result
          const data = res.result //表
          data.forEach((i: any) => {
            if (i.contractStatus == 3 || i.contractStatus == 7 || i.contractStatus == 10) {
              i.disabled = false
            } else {
              i.disabled = true
            }
          })
          console.log('data', data)
          tableCompulsory.dataList = data
          if (tableCompulsory.dataList.length) {
            orderCode.value = tableCompulsory.dataList[0].orderCode
          }
        })
        .finally(() => {
          tableCompulsory.tableLoading = false
        })
    }
  }
  const tableCompulsory = useTable({
    pagination: false,
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: true,
    },
    columns: [
      // { title: '', slotName: 'selectkey', width: 120, fixed: 'left' },
      { title: '合同编号', dataIndex: 'contractNo', fixed: 'left', width: 240 },
      {
        title: '合同属性',
        dataIndex: 'contractAttributeName',
        titleSlotName: 'attribute',
        cellStyle: { width: props.orderType == 2 ? 240 : 0 },
      },
      { title: '合同类型', dataIndex: 'contractTypeName' },
      { title: '合同模板名称', dataIndex: 'templateName', width: 240 },
      { title: '归属门店', dataIndex: 'siteName', width: 240 },
      { title: '合同状态', dataIndex: 'endTime', width: 300, slotName: 'contractStatus' },
      { title: '承租方', slotName: 'lessee' },
      { title: '出租方', dataIndex: 'tenantName' },
      { title: '签署短信条数', dataIndex: 'msgNum', titleTooltipContent: '发送签署链接的短信会单独收费' },
      { title: '发起人', dataIndex: 'startPersonName' },
      { title: '发起签署时间', dataIndex: 'startTime', width: 200 },
      { title: '发起节点', dataIndex: 'startNode' },
    ],
    tableLoading: false,
    operates: [
      {
        // dev-ok
        label: '预览',
        show: (record: any) =>
          record.contractStatus != 9 &&
          record.contractStatus != 10 &&
          record.contractStatus != 11 &&
          record.contractStatus != -1 &&
          record.contractStatus != -2,
        permission: getPermission('contractPreview'),
        method: (record: any) => {
          console.log(record)
          request
            .post(
              '/svmsContract/downloadContractFile',
              {
                id: record.id,
                type: 1,
              },
              {
                responseType: 'blob',
              }
            )
            .then((res) => {
              console.log(res)
              const binaryData = []
              binaryData.push(res.data)
              let url = window.URL.createObjectURL(new Blob(binaryData, { type: 'application/pdf' }))
              window.open(url)
              // Object.assign(pdfViewInfo, {
              //   url,
              //   title: record.contractTypeName + record.contractNo,
              //   show: true,
              // })
            })
        },
      },
      {
        label: '发送签署短信',
        permission: getPermission('contractSendSigningSms'),
        show: (record: any) => record.contractStatus == 2,
        method: (record: any) => {
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            content: `发送签署短信会产生短信费用，请确认是否发送?`,
            onOk: () => {
              sendLesseeSignMsg({ id: record.id }).then((res: any) => {
                console.log('发送签署短信', res)
                Message.success('已将合同签署链接发送至当前合同的承租人手机号')
                loadCompulsoryData()
              })
            },
          })
        },
      },
      {
        label: '修改合同',
        permission: getPermission('contractModify'),
        show: (record: any) => record.contractStatus == 2,
        method: (record: any) => {
          getContractInfo({ id: record.id, orderType: props.orderType, contractType: record.contractType }).then((res: any) => {
            res.result.contractFee.forEach((item: any) => {
              item.value = +item.value
            })

            viewContractInfo.value = {
              ...res.result,
              contractType: record.contractType,
              contractId: record.id,
              timeRange: [res.result.startTime, res.result.endTime],
              sendServiceFlag: res.result.sendServiceFlag == 1 ? true : false,
              returnServiceFlag: res.result.returnServiceFlag == 1 ? true : false,
              payType: props.payType,
              method: 'update',
            }

            console.log('修改合同', res, viewContractInfo.value)
            viewVisible.value = true
          })
        },
      },
      {
        // dev-ok
        label: '撤回',
        permission: getPermission('contractWithdraw'),
        show: (record: any) => record.contractStatus == 2,
        method: (record: any) => {
          console.log(record)
          if (record.lesseeSignStatus == 1 || record.hireSignStatus == 1) {
            Modal.confirm({
              title: '提示',
              simple: true,
              cancelText: '取消',
              okText: '确认',
              content: `合同撤回后，承租方签署链接失效，无法完成签署，确认撤回吗？`,
              onOk: () => {
                revokeAPI({ id: record.id }).then(() => {
                  Message.success('操作成功')
                  loadCompulsoryData()
                })
              },
            })
          } else if (record.orderStatus == -100 || record.orderStatus == -1000) {
            revokeAPI({ id: record.id }).then(() => {
              Message.success('操作成功')
              loadCompulsoryData()
            })
          }
        },
      },
      {
        // dev-ok
        label: '下载',
        permission: getPermission('contractDownload'),
        show: (record: any) =>
          record.contractStatus == 3 || record.contractStatus == 7 || record.contractStatus == 8 || record.contractStatus == 10,
        method: (record: any) => {
          console.log(record)
          if (record.contractStatus == 10) {
            window.open(import.meta.env.VITE_BASE_PATH + `/download/downloadById?fileId=${record.contractFileId}`)
          } else {
            request
              .post(
                '/svmsContract/downloadContractFile',
                {
                  id: record.id,
                  type: 0,
                },
                {
                  responseType: 'blob',
                }
              )
              .then((res) => {
                console.log(res)
                fileDownload(res.data, 'justone', record)
              })
          }
        },
      },
      {
        label: '作废',
        permission: getPermission('contractInitiateCancellation'),
        show: (record: any) => record.contractStatus == 3,
        method: (record: any) => {
          console.log(record)
          // 一.if企业,有无手机号
          if (record.leaseType == 1) {
            // 企业
            // 查询企业信息(是否包含手机号)
            getDetail({ id: record.lesseeId }).then((res: any) => {
              clientData.value = res.result
              if (res.result.mobile && res.result.linkman) {
                // 1.有企业手机号
                nullifyFn(record)
              } else {
                // 2.没有企业手机号, 发起手机号填写弹窗
                addphones.value.show(record, 'b', clientData.value)
              }
            })
          } else {
            nullifyFn(record)
          }
        },
      },
    ],
  })
  // 发起签署
  const initiateFn = (record: any) => {
    Modal.confirm({
      title: '提示',
      simple: true,
      cancelText: '取消',
      okText: '确认',
      content: `请确认是否要发起合同签署?`,
      onOk: () => {
        // 发起签署接口
        initiateAPI({ id: record.id }).then(() => {
          // 企业/个人 提示不同
          if (record.leaseType == 1) {
            // 企业
            Modal.confirm({
              title: '提示',
              simple: true,
              hideCancel: true,
              okText: '关闭',
              content: `已将合同信息以短信的形式发送至企业联系人手机，并等待签署`,
              onOk: () => {
                loadCompulsoryData()
              },
            })
          } else {
            // 个人
            Modal.confirm({
              title: '提示',
              simple: true,
              hideCancel: true,
              okText: '关闭',
              content: `已将合同信息以短信的形式发送至承租人手机，并等待签署`,
              onOk: () => {
                loadCompulsoryData()
              },
            })
          }
          loadCompulsoryData()
        })
      },
    })
  }
  // 发起作废
  const nullifyFn = (record: any) => {
    Modal.confirm({
      title: '提示',
      simple: true,
      cancelText: '取消',
      okText: '确认',
      content: `合同已完成签署，确认作废吗?`,
      onOk: () => {
        // 发起作废接口
        nullifyAPI({ id: record.id }).then(() => {
          loadCompulsoryData()
        })
      },
    })
  }
  // 带回电话
  const addphoneFn = (recordData: any) => {
    console.log('recordData-----------', recordData)
    // 补充电话
    if (recordData.type == 'a') {
      // 调用发起签署补充电话的接口(编辑企业客户接口)
      clientupdate({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then((res: any) => {
        console.log('编辑企业客户接口 ---- 补充电话')
        console.log(res)
        // 判断余额
        determineAPI({ orderId: props.orderId, orderType: props.orderType }).then((res: any) => {
          if (res.result.determine) {
            // 1.足够
            // 发起签署
            initiateFn(recordData.record)
          } else {
            // 2.不够
            Modal.confirm({
              title: '提示',
              simple: true,
              hideCancel: true,
              okText: '关闭',
              content: `账户余额不足，请先联系工作人员充值，再进行操作`,
            })
            return false
          }
        })
      })
    }
    if (recordData.type == 'b') {
      // 调用发起作废补充电话的接口
      clientupdate({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then((res: any) => {
        console.log('编辑企业客户接口 ---- 补充电话')
        console.log(res)
        // 发起作废
        nullifyFn(recordData.record)
      })
    }
    if (recordData.type == 'c') {
      // 调用生成电子合同补充电话的接口
      clientupdate({
        id: clientData.value.id,
        clientName: clientData.value.clientName,
        mobile: recordData.phone,
        linkman: recordData.linkman,
      }).then((res: any) => {
        console.log('编辑企业客户接口 ---- 补充电话')
        console.log(res)
        // 生成电子合同
        contractGet(recordData.record)
      })
    }
  }
  // 快速复制
  const getLesseeSignUrl = (record: any) => {
    getLesseeSignUrlAPI({ id: record.id }).then((res: any) => {
      console.log(res)
      // 复制res.result
      copyurl.value = res.result
      toClipboard(copyurl.value)
      if (record.contractStatus == 2 || record.contractStatus == 3 || record.contractStatus == 8) {
        Message.success('已将链接复制到剪切板')
      }
      if (record.contractStatus == 7) {
        Message.success('承租方作废链接已复制到剪切板')
      }
    })
  }
  const editCurrentMemberModalRef = ref()
  const changeMemberFn = (data: any) => {
    editCurrentMemberModalRef.value.close()
    editLesseeMemberModalRef.value.open(orderDetails.value, data)
  }
  // 排车 & 改排
  const carSelectorRef = ref()
  const carSelectorModalTitle = ref('排车')
  const platoonCarFn = (record: any) => {
    let status = record.orderStatus || record.status
    if ([10, 100].includes(status)) {
      const param = {
        // siteId: record.siteId,
        dateRange: [record.startTime || record.expectedUseCarTime, record.endTime || record.expectedReturnCarTime],
        id: record.id,
        carSource: record.carSource,
      }
      if (status == 10) {
        carSelectorModalTitle.value = '排车'
      } else {
        carSelectorModalTitle.value = '改排'
      }
      carSelectorRef.value.open(param, {
        ...record,
        modelId: record.carModelId || record.modelId,
        startTime: record.startTime || record.expectedUseCarTime,
        endTime: record.endTime || record.expectedReturnCarTime,
        rentDays: record.rentDays || record.leaseNumberStr,
        carModelName: record.carModelName || record.modelName,
        platoonCarId: status == 100 ? record.carId : undefined,
      })
    }
  }

  // 修改车牌号判断订单是否有换车操作弹框
  const changeLicenseModalRef = ref()
  // 换车记录列表
  const orderCarInfoList = ref([])
  const editCarLicenseNo = (record: any) => {
    let fn = props.orderType == 1 ? carReplaceList : updateReplaceList
    fn({ id: record.id }).then((res: any) => {
      let result = res.result
      // 是否为换车
      if (result.orderCarInfoList?.length > 1) {
        orderCarInfoList.value = result.orderCarInfoList.map((item: any) => {
          return {
            ...item,
            label: item.licenseNo,
            value: item.id,
          }
        })
        changeLicenseModalRef.value.open(record)
      } else {
        changeLicenseOk(record)
      }
    })
  }
  // 修改车牌号跳转操作
  const changeLicenseOk = (record: any) => {
    const param = {
      modelId: record.carModelId,
      dateRange: [record.startTime, record.endTime],
      carSource: record.carSource,
      oldOrderCarId: record.oldOrderCarId,
      isEditLicenseNo: true, // 修改车牌号标识
    }
    carSelectorModalTitle.value = '修改车牌号'
    carSelectorRef.value.open(param, {
      ...record,
      modelId: record.carModelId,
      platoonCarId: record.orderStatus == 100 ? record.carId : undefined,
    })
  }

  const editLesseeMemberModalRef = ref()
  const errorModalFn = () => {
    return new Promise<void>(async (resolve, reject) => {
      // 生成电子合同判断逻辑优化
      let okText = '去匹配',
        cancelText = '取消',
        onOk,
        onCancel,
        content: any,
        hideCancel = false
      let { result } = await checkContractData({ orderId: props.orderId, orderType: props.orderType })
      let keys = Object.keys(result)
      if (keys.length) {
        let status = keys[0]
        switch (Number(status)) {
          // 门店信息为空
          case 9901:
            okText = '去匹配'
            content = h('div', { class: 'text-center' }, [
              h('div', null, [
                h('span', null, `当前订单`),
                h(
                  'span',
                  {
                    style: {
                      color: 'red',
                    },
                  },
                  `无门店`
                ),
              ]),
              h('div', null, [
                h('span', null, `请完成`),
                h('span', { class: 'modalText' }, `当前渠道订单门店的匹配，`),
                h('span', null, `再生成电子合同`),
              ]),
            ])
            onOk = () => {
              let accountSubject = orderDetails.value.accountSubject.split('，').slice(-1).join('')
              usePermission('svms:business:channel:ota.edit')
                ? navigateTo(`/channel-setting/edit/${orderDetails.value.accountId}?tabKey=2`, `${accountSubject}-编辑渠道`)
                : Message.error('您没有OTA渠道管理的编辑权限')
            }
            break
          // 姓名或手机号格式不正确
          case 9902:
            let infoArr = result[keys[0]].split(' ')
            okText = '去修改'
            content = h('div', null, [
              h('p', null, `承租人信息 ${infoArr.filter((_: any, index: any) => index != 2).join(' ')}`),
              h('div', null, [
                h('span', null, `当前订单承租人的`),
                h('span', { class: 'modalText' }, `${infoArr.slice(-1).join()}`),
                h('span', null, `格式错误`),
              ]),
              h('div', null, [
                h('span', null, `请先修改承租人`),
                h('span', { class: 'modalText' }, `${infoArr.slice(-1).join()}，`),
                h('span', null, `再生成电子合同`),
              ]),
            ])
            onOk = () => {
              let permissionStr = props.orderType == 1 ? 'svms:order:short-order.edit' : 'svms:order:long-order.edit'
              usePermission(permissionStr) ? editCurrentMemberModalRef.value.open(orderDetails.value) : Message.error('您没有订单修改权限')
            }
            break
          // 处于待排车状态的手动维护渠道订单和线下订单
          case 9903:
            okText = '去排车'
            cancelText = '继续生成'
            content = h('div', null, [
              h('div', { class: 'text-center' }, [
                h('span', null, `当前订单`),
                h(
                  'span',
                  {
                    style: {
                      color: 'red',
                    },
                  },
                  `未排车`
                ),
              ]),
              h('div', null, [
                h('span', null, '点击【去排车】先完成'),
                h('span', { class: 'modalText' }, '当前订单的排车，'),
                h('span', null, '再生成电子合同'),
              ]),
              h('p', null, `点击【继续生成】，合同生成后可通过【修改合同】完善车辆信息`),
            ])
            onOk = () => {
              let permissionStr = props.orderType == 1 ? 'svms:order:short-order.platooncar' : 'svms:order:long-order.platooncar'
              usePermission(permissionStr) ? platoonCarFn(orderDetails.value) : Message.error('您没有排车权限')
            }
            onCancel = () => resolve()
            break
          // 处于待排车状态的自动维护的渠道订单
          case 9904:
            okText = '取消'
            cancelText = '继续生成'
            content = h('div', null, [
              h('div', { class: 'text-center' }, [
                h('span', null, `当前订单`),
                h(
                  'span',
                  {
                    style: {
                      color: 'red',
                    },
                  },
                  `未排车`
                ),
              ]),
              h('p', null, `可先在渠道平台完成订单的排车，再生成电子合同`),
              h('p', null, `点击【继续生成】，合同生成后可通过【修改合同】完善车辆信息`),
            ])
            onOk = () => reject()
            onCancel = () => resolve()
            break
          // 自动维护的且有渠道车辆有值的渠道订单到达待用车的状态后,订单上仍没有排车车辆
          case 9905:
            okText = '去匹配'
            cancelText = '继续生成'
            content = h('div', null, [
              h('div', { class: 'text-center' }, [
                h('span', null, `当前订单`),
                h(
                  'span',
                  {
                    style: {
                      color: 'red',
                    },
                  },
                  `无车辆`
                ),
              ]),
              h('div', null, [
                h('span', null, '点击【去匹配】先完成'),
                h('span', { class: 'modalText' }, '当前渠道订单车辆的匹配，'),
                h('span', null, '再生成电子合同'),
              ]),
              h('p', null, `点击【继续生成】，合同生成后可通过【修改合同】完善车辆信息`),
            ])
            onOk = () => {
              let accountSubject = orderDetails.value.accountSubject.split('，').slice(-1).join('')
              usePermission('svms:business:channel:ota.edit')
                ? navigateTo(`/channel-setting/edit/${orderDetails.value.accountId}?tabKey=4`, `${accountSubject}-编辑渠道`)
                : Message.error('您没有OTA渠道管理的编辑权限')
            }
            onCancel = () => resolve()
            break
          // 自动维护的但是渠道车辆为空的渠道订单到达待用车状态后，订单上仍没有排车车辆
          case 9906:
            okText = '修改车牌号'
            cancelText = '继续生成'
            content = h('div', null, [
              h('div', { class: 'text-center' }, [
                h('span', null, `当前订单`),
                h(
                  'span',
                  {
                    style: {
                      color: 'red',
                    },
                  },
                  `无车辆`
                ),
              ]),
              h('p', null, [
                h('span', null, '点击【修改车牌号】先填写'),
                h('span', { class: 'modalText' }, '车牌号，'),
                h('span', null, '再生成电子合同'),
              ]),
              h('p', null, `点击【继续生成】，合同生成后可通过【修改合同】完善车辆信息`),
            ])
            onOk = () => {
              let permissionStr =
                props.orderType == 1 ? 'svms:order:short-order.editCarLicenseNo' : 'svms:order:long-order.editCarLicenseNo'
              usePermission(permissionStr) ? editCarLicenseNo(orderDetails.value) : Message.error('您没有修改车牌号的权限')
            }
            onCancel = () => resolve()
            break
          // 承租人不存在系统会员中，获取不到会员信息
          case 9907:
            okText = '确认'
            hideCancel = true
            content = result[keys[0]]
            onOk = () => reject()
            break
        }
        Modal.info({
          maskClosable: false,
          width: 500,
          title: '提示',
          content: () => content,
          hideCancel: hideCancel || false,
          okText,
          cancelText,
          onOk,
          onCancel,
        })
        return
      }
      resolve()
    })
  }

  const improveInformationRef = ref()
  const onClick = async () => {
    await errorModalFn()
    viewContractInfo.value = null

    getContractInfo({ orderId: props.orderId, orderType: props.orderType, contractType: 1 }).then((res: any) => {
      res.result.contractFee.forEach((item: any) => {
        item.value = +item.value
      })

      viewContractInfo.value = {
        ...res.result,
        orderId: props.orderId,
        orderType: props.orderType,
        operationType: 0,
        contractType: 1,
        payType: props.payType,
        contractId: null,
        method: 'create',
      }
    })

    viewVisible.value = true
  }

  const improveInformationOnOk = () => {
    getOrdersDetails()
  }

  const onOkContract = (options: any) => {
    viewLoading.value = true

    const { detail } = options

    console.log('detail', detail)

    if (detail.contractId) {
      updateFreeContract({ ...detail, id: detail.contractId })
        .then((res: any) => {
          console.log('updateFreeContract', res)

          if (res.result?.resultErrorCode == 9999) {
            Modal.confirm({
              title: '提示',
              simple: true,
              hideCancel: false,
              okText: '去上传',
              onOk: () => {
                // 去上传
                usePermission('svms:business:contract:template.edit')
                  ? navigateTo(
                      `/contract/template/edit/${res.result.templateId}?orderType=${props.orderType}`,
                      `${res.result.templateName}-编辑合同模板`
                    )
                  : Message.error('您没有合同模板的编辑权限')
              },
              cancelText: '取消',
              content: targetStrColor(res.result.resultErrorMsg, '公司印章', { color: 'red' }),
            })
          } else {
            viewVisible.value = false
            loadCompulsoryData()

            if (props.orderType == 1) {
              getContractCountShortOrder()
            } else {
              getContractCountLongOrder()
            }
          }
        })
        .finally(() => {
          viewLoading.value = false
        })
    } else {
      createContractAPI({
        orderType: props.orderType,
        orderCode: orderDetails.value.orderCode,
        contractType: detail.contractType,
        id: detail?.contractId,
        operationType: detail?.operationType,
        payType: props.payType,
        contractFee: detail.contractFee,
        startCarMileageContract: detail.startCarMileageContract,
        startCarOilContract: detail.startCarOilContract,
      })
        .then((res: any) => {
          if (res.result.resultErrorCode == 9999) {
            Modal.confirm({
              title: '提示',
              simple: true,
              hideCancel: false,
              okText: '去上传',
              onOk: () => {
                // 去上传
                usePermission('svms:business:contract:template.edit')
                  ? navigateTo(
                      `/contract/template/edit/${res.result.templateId}?orderType=${props.orderType}`,
                      `${res.result.templateName}-编辑合同模板`
                    )
                  : Message.error('您没有合同模板的编辑权限')
              },
              cancelText: '取消',
              content: targetStrColor(res.result.resultErrorMsg, '公司印章', { color: 'red' }),
            })
          } else if (res.result.createErrorCode) {
            viewVisible.value = false
            if (res.result.createErrorCode == 1001) {
              // 生成失败弹窗
              // 1. 姓名手机号不匹配时
              toError({ orderCode: orderDetails.value.orderCode })
            } else {
              // 生成失败弹窗
              // 2. 其他原因（没有前往修改按钮）
              Modal.confirm({
                title: '提示',
                simple: true,
                hideCancel: true,
                okText: '关闭',
                content: res.result.createErrorReason,
              })
              loadCompulsoryData()

              if (props.orderType == 1) {
                getContractCountShortOrder()
              } else {
                getContractCountLongOrder()
              }
            }
          } else if (res.result.createErrorCode == null) {
            Message.success('操作成功')
            loadCompulsoryData()

            if (props.orderType == 1) {
              getContractCountShortOrder()
            } else {
              getContractCountLongOrder()
            }
            viewVisible.value = false
          }
        })
        .finally(() => {
          viewLoading.value = false
        })
    }
  }

  const orderDetails = ref()
  const viewContractInfo = ref()

  const getOrdersDetails = (callback?: Function) => {
    if (props.orderType == 1) {
      getShortOrdrDetails({ id: props.orderId }).then((res: any) => {
        orderCode.value = res.result.orderInfo.orderCode
        orderDetails.value = res.result.orderInfo
        // orderCode.value = 'XC702022111500147'
        if (orderCode.value) {
          loadCompulsoryData()
        }

        callback && callback()
      })
    } else {
      getLongOrderDetails({ id: props.orderId }).then((res: any) => {
        orderDetails.value = {
          ...res.result.orderInfo,
          carLicenseNo: res.result.orderInfo.licenseNo,
          orderCode: res.result.orderInfo.orderNo,
          startTime: res.result.orderInfo.expectedUseCarTime,
          endTime: res.result.orderInfo.expectedReturnCarTime,
          rentDays: res.result.orderInfo.leaseNumberStr,
          carModelName: res.result.orderInfo.modelName,
          totalAmount: res.result.orderInfo.carRentAmount,
          carDeposit: res.result.orderInfo.carDepositAmount,
          illegalDeposit: res.result.orderInfo.violationDepositAmount,
          orderStatus: res.result.orderInfo.status,
        }
        loadCompulsoryData()

        callback && callback()
      })
    }
  }

  const onModalOkFn = () => {
    emits('ok')
  }

  onMounted(() => {
    console.log('free onMounted')
    // 获取企业联系人id
    if (props.orderId) {
      getOrdersDetails(() => {
        // 地址栏传入 triggerNewContract 时，默认打开新合同弹窗
        let triggerNewContract: any = sessionStorage.getItem('triggerNewContract')
        if (triggerNewContract == 81) {
          onClick()
          sessionStorage.removeItem('triggerNewContract')
        }
      })
    }
  })
</script>
<style>
  .modalText {
    color: #3491fa;
    font-weight: 700;
  }
</style>
<style scoped lang="less">
  .alert_download {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 20px;
  }

  .download-button {
    display: inline-block;
    height: 32px;
    margin-left: 12px;
    line-height: 32px;
    padding: 0 15px;
    font-size: 14px;
    color: #fff;
    background-color: rgb(var(--primary-6));
    border: 1px solid transparent;
    cursor: pointer;
  }
  .res-button {
    display: inline-block;
    margin-top: 4px;
    padding: 0 8px;
    font-size: 12px;
    border-radius: 2px;
    color: #fff;
    background-color: rgb(var(--primary-6));
    border: 1px solid transparent;
    cursor: pointer;
  }
  .status_copys {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-top: 4px;
  }
  .lessee_sign_status_1 {
    color: #ff7d00;
    border: 1px solid #ff7d00;
    background-color: #fff7e8;
    font-size: 12px;
    padding: 0 8px;
    border-radius: 2px;
  }
  .lessee_sign_status_2 {
    color: #00b42a;
    border: 1px solid #00b42a;
    background-color: #e8ffea;
    font-size: 12px;
    padding: 0 8px;
    border-radius: 2px;
  }
  .copy_link {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    color: #3491fa;
    text-decoration: underline;
    cursor: pointer;
    img {
      width: 20px;
      height: 20px;
    }
  }
  .contract-statusname {
    font-size: 14px;
    font-weight: 400;
  }
  .contract-statusname-1 {
    // 未发起
    color: #c7c7c7;
  }
  .contract-statusname-2 {
    // 签署中
    color: #3491fa;
  }
  .contract-statusname-3 {
    // 已完成
    color: #00b42a;
  }
  .contract-statusname-4 {
    // 已撤回
    color: #f53f3f;
  }
  .contract-statusname-5 {
    // 已撤回
    color: #f53f3f;
  }
  .contract-statusname-6 {
    // 已截止
    color: #f53f3f;
  }
  .contract-statusname-7 {
    // 作废中
    color: #ff7d00;
  }
  .contract-statusname-8 {
    // 已作废
    color: #f53f3f;
  }
  .contract-statusname-9 {
    // 无效
    color: #722ed1;
  }
  .contract-statusname--1 {
    // 生成失败
    color: #f53f3f;
  }
  .lessee_sign {
    margin: 0 8px 0;
  }
  .hire_sign {
    margin: 0 8px 0;
  }
  .a-alert {
    font-size: 14px;
    font-weight: 400;
    color: #1d2129;
    flex: 1;
  }
</style>
